package kn.pulldata.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;

@Component
public class RedisLockUtils {
    private static final String LOCK_PREFIX = "lock:";


    @Autowired
    @Qualifier("redisTemplateWithString")
    private RedisTemplate<String, String> redisTemplate;


    /**
     *  加锁
     **/
    public Boolean getLock(String key,String value,long time){
        return this.redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + key,value, Duration.ofHours(time));
    }

    /**
     *  释放锁
     **/
    public Long releaseLock(String key,String value){
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class);
        Long releaseStatus = (Long)this.redisTemplate.execute(redisScript, Collections.singletonList(key),value);
        return releaseStatus;
    }

}
